/********************************************************************
*                                                                   *
* Microsoft Windows Sidebar Gadget for NNTT.ORG                     *
* Released under the MIT license by Alexey Glukharev, Januar 2012.  *
*                                                                   *
********************************************************************/

//----------------------------------------
// Global variables
//---
var forums_data =[];
var forums_tree =[];

//----------------------------------------
// Enable crossdomain interaction
//---
jQuery.support.cors = true;

//----------------------------------------
// Script entry point
//---
$(document).ready(function () {
    // Set close settings window handler
    System.Gadget.onSettingsClosing = settingsClosing;
    
    // Create tabs
    $("#tabs").tabs({
        select: function (event, ui) {
            // Fill the tree forums takes a long time,
            // so start working with a tree only at the first
            // reference to the tab. The next switching ignored
            if (($(ui.panel).attr("id") == "releases") && ($(ui.panel).data("once") == undefined)) {
                $(ui.panel).data("once", "true")
                loadForumsList();
            }
        }
    });
    
    // Init control buttons
    $("#addProfile").click(function () {
        showProfileDialog(saveProfile);
        return false;
    });
    
    $("#editProfile").click(function () {
        showProfileDialog(function () {
            var selectedProfile = $("#default-profile").val();
            return saveProfile(selectedProfile);
        },
        fillProfile);
        return false;
    });
    
    $("#deleteProfile").click(function () {
        var selectedProfile = $("#default-profile").val();
        if (typeof (selectedProfile) != 'undefined' && selectedProfile != null) {
            Settings().getProfileManager().remove(selectedProfile);
            refreshProfilesList(selectedProfile);
        }
        return false;
    });
    
    setUIState();
});

//----------------------------------------
// Handlers
//---
function settingsClosing(event) {
    if (event.closeAction == event.Action.commit) {
        // Save the settings
        Settings().set('defaultSearchType', $('#search-type').val());
        Settings().set('dataRefreshPeriod', $('#data-refresh-period').val());
        Settings().set('panelsTogglePeriod', $('#panels-toggle-period').val());
        Settings().set('lastNewsPeriod', $('#last-news-period').val());
        Settings().set('statisticPeriod', $('#statistic-period').val());
        
        // 'null' means that the profiles are not created
        var defProfile = $('#default-profile').val();
        if (defProfile == null) {
            defProfile = "";
        }
        Settings().set('defaultProfile', defProfile);
        
        // If the tree is ready (visible), process it
        if ($("#forums").is(":visible")) {
            // Get a list of the selected forums
            var ids =[];
            $("#forums").jstree("get_checked", null, true).each(function () {
                ids.push($(this).attr("id"));
            });
            
            Settings().set('forumsList', ids);
        }
        
        // Write settings to storage
        Settings().save();
    }
}

//----------------------------------------
// Initialisation functions
//---
function setUIState() {
    $("#panels-toggle-period option[value='" + Settings().get('panelsTogglePeriod') + "']").attr("selected", "selected");
    $("#search-type option[value='" + Settings().get('defaultSearchType') + "']").attr("selected", "selected");
    $("#data-refresh-period option[value='" + Settings().get('dataRefreshPeriod') + "']").attr("selected", "selected");
    $("#last-news-period option[value='" + Settings().get('lastNewsPeriod') + "']").attr("selected", "selected");
    $("#statistic-period option[value='" + Settings().get('statisticPeriod') + "']").attr("selected", "selected");
    
    // Fill the list of available profiles and select default profile
    refreshProfilesList(Settings().get('defaultProfile'));
}

//----------------------------------------
// Working with DOM
//---
function buildTree(parent_id, parent_node) {
    // Process the descendants array
    for (var c = 0; c < forums_tree[parent_id].length; c++) {
        var item_id = forums_tree[parent_id][c];
        
        // Create a child node "li"
        var li = $("<li>", {
            "id": item_id,
            html: $("<a>", {
                html: forums_data[item_id].forum_name,
                "title": forums_data[item_id].forum_name,
                click: function (event) {
                    event.preventDefault();
                }
            })
        })
        .appendTo($(parent_node));
        
        // Is a child itself in the list of parents?
        if (typeof (forums_tree[item_id]) != 'undefined') {
            // Child is a parent, start the recursion by adding a new parent
            var ul = $("<ul>").appendTo($(li));
            buildTree(item_id, ul);
        } else {
            // Child is not among the parents - thus he has no children
        }
    }
}

// Функция заполняет element списком доступных профилей настроек torrent-клиентов
function fillProfilesList(element) {
    if (typeof (element) == 'undefined' || element == null) {
        return;
    }
    
    $(element).html("");
    var list = Settings().getProfileManager().getProfilesList();
    for (var i = 0; i < list.length; i++) {
        $(element).append("<option value='" + list[i] + "'>" + list[i] + "</option>");
    }
    
    // Set profile control buttons state
    if (list.length > 0) {
        $("#deleteProfile,#editProfile").removeAttr('disabled');
    } else {
        $("#deleteProfile,#editProfile").attr('disabled', 'disabled');
    }
}

//----------------------------------------
// Ajax functions
//---
function loadForumsList() {
    $("#forums-loading-info").html("<span class='center-wrapper'><span><p class='load-message'><img src='images/load.gif' class='gadget-icon'/>" + strings[ 'forumsTreeLoading'] + "</p></span></span>");
    
    $.ajax({
        cache: false,
        type: "POST",
        url: "http://www.nntt.org/ajax.php",
        data: {
            action: "latest_torrents", "get_forums": true, count: 1
        },
        dataType: "json",
        error: function (error) {
            $("#forums-loading-info").html("<span class='center-wrapper'><span><p class='load-message'><img src='images/error.png' class='gadget-icon'/>" + strings[ 'error'] + error.statusText + "</p></span></span>");
        },
        success: function (msg) {
            $("#forums-loading-info").html("<span class='center-wrapper'><span><p class='load-message'><img src='images/load.gif' class='gadget-icon'/>" + strings[ 'forumsTreeDataPrepare'] + "</p></span></span>");
            
            if (typeof (msg.forums) != 'undefined' && msg.forums.length > 0) {
                for (var i = 0; i < msg.forums.length; i++) {
                    
                    // Fill the array with the data
                    forums_data[msg.forums[i].forum_id] = {
                        "forum_id": msg.forums[i].forum_id,
                        "parent_id": msg.forums[i].parent_id,
                        "forum_name": msg.forums[i].forum_name
                    }
                    
                    // Fill the array "parent-children"
                    if (typeof (forums_tree[msg.forums[i].parent_id]) == 'undefined') {
                        forums_tree[msg.forums[i].parent_id] =[];
                    }
                    
                    forums_tree[msg.forums[i].parent_id].push(msg.forums[i].forum_id);
                }
                
                // Root element of the tree
                $("<ul>", {
                    html: $("<li>", {
                        "id": "0",
                        html: $("<a>", {
                            html: strings[ 'allForums'],
                            click: function (event) {
                                event.preventDefault();
                            }
                        })
                    })
                    .append($("<ul>", {
                        id: "root-item"
                    }))
                })
                .appendTo($("#forums"));
                
                // Now process the structure recursively
                buildTree(0, $("#root-item"));
                
                // Now build tree
                $("#forums-loading-info").html("<span class='center-wrapper'><span><p class='load-message'><img src='images/load.gif' class='gadget-icon'/>" + strings[ 'forumsTreeBuilding'] + "</p></span></span>");
                $("#forums")
                .bind("loaded.jstree", function (e) {
                    $("#forums-loading-info").html("<span class='center-wrapper'><span><p class='load-message'><img src='images/load.gif' class='gadget-icon'/>" + strings[ 'forumsTreeConfig'] + "</p></span></span>");
                    
                    // Try to load a saved forum's list
                    // and select checkboxes according it
                    var forumsList = Settings().get("forumsList")
                    for (var i = 0; i < forumsList.length; i++) {
                        if (forumsList[i].length > 0) {
                            $("#forums").jstree("check_node", $("#" + forumsList[i]));
                        }
                    }
                    
                    // We are ready to show tree now
                    $("#forums-loading-info").hide();
                    $(this).show();
                })
                .jstree({
                    core: {
                        animation: 0,
                        initially_open:[ "#0"]
                    },
                    themes: {
                        theme: "default",
                        url: "css/themes/default/style.css",
                        icons: false
                    },
                    checkbox: {
                        two_state: true,
                        override_ui: true,
                        checked_parent_open: false
                    },
                    contextmenu: {
                        items: function (node) {
                            // Menu is only available if there is subforums
                            if ($(node).is(":has(ul)")) {
                                return {
                                    "selectAll": {
                                        "label": strings[ 'selectAll'],
                                        "action": function (obj) {
                                            this.check_node(obj);
                                            this.check_node($(obj).find("li"));
                                        }
                                    },
                                    "unselectAll": {
                                        "label": strings[ 'unselectAll'],
                                        "action": function (obj) {
                                            this.uncheck_node(obj);
                                            this.uncheck_node($(obj).find("li"));
                                        }
                                    }
                                }
                            } else {
                                return;
                            }
                        }
                    },
                    plugins:[ "themes", "html_data", "checkbox", "ui", "contextmenu"]
                });
            }
        }
    });
}

//----------------------------------------
// Helper function
//---
function showProfileDialog(accepted, init) {
    $("#profile-popup").find("input[type='text'],input[type='password']").val('');
    $("#profile-popup").dialog({
        draggable: false,
        modal: true,
        width: "230px",
        resizable: false,
        buttons: {
            "Save": function () {
                if (typeof (accepted) != 'undefined' && accepted != null && accepted.call()) {
                    $(this).dialog("destroy");
                }
            },
            "Close": function () {
                $(this).dialog("destroy");
            }
        },
        open: function () {
            if (typeof (init) != 'undefined' && init != null) {
                init();
            }
        }
    });
}

function showErrorMsg(msg) {
    $("<div>", {
        html: msg,
        title: strings[ 'profileError']
    })
    .dialog({
        draggable: false,
        modal: true,
        width: "230px",
        resizable: false,
        buttons: {
            "OK": function () {
                $(this).dialog("destroy");
            }
        }
    });
}

function saveProfile(editProfile) {
    var profileName = $('#profile-name').val().trim();
    var torrentClient = $('#torrent-client').val();
    var transportProtocol = $('#transport-protocol').val();
    var torrentHost = $('#web-ui-host').val().trim();
    var torrentPort = $('#web-ui-port').val().trim();
    var torrentUser = $('#web-ui-user').val().trim();
    var torrentPass = $('#web-ui-pass').val().trim();
    
    // Если все текстовые поля заполнены, продолжаем сохранение, а иначе ругаемся
    if (profileName != null && profileName.length > 0 &&
    torrentHost != null && torrentHost.length > 0 &&
    torrentPort != null && torrentPort.length > 0 &&
    torrentUser != null && torrentUser.length > 0 &&
    torrentPass != null && torrentPass.length > 0) {
        
        // Если мы правим существующий профиль
        if (typeof (editProfile) != 'undefined' && editProfile != null) {
            editProfile = editProfile.trim();
            
            // Проверим, изменилось ли имя профиля
            if (editProfile.length > 0 && editProfile != profileName) {
                // Новое имя не должно совпадать с другими
                if (Settings().getProfileManager().isExist(profileName)) {
                    showErrorMsg(strings[ 'profileNameNotUnique']);
                    return false;
                }
            }
            
            // Удалим старую версию
            // Редактированная версия записывается заново
            Settings().getProfileManager().remove(editProfile);
        } else {
            // Создаётся новый профиль
            // Его имя не должно совпадать с другими
            if (Settings().getProfileManager().isExist(profileName)) {
                showErrorMsg(strings[ 'profileNameNotUnique']);
                return false;
            }
        }
        
        // Сохраняем профиль
        Settings().getProfileManager().add({
            name: profileName,
            client: torrentClient,
            protocol: transportProtocol,
            host: torrentHost,
            port: torrentPort,
            user: torrentUser,
            password: torrentPass
        });
        
        // Одновим список профилей
        refreshProfilesList(profileName);
        
        return true;
    } else {
        // Ругаемся на правильность заполнения
        showErrorMsg(strings[ 'emptyFields']);
    }
    
    return false;
}

function fillProfile() {
    var defProfile = $("#default-profile").val();
    if (typeof (defProfile) != 'undefined' && defProfile != null && defProfile.length > 0) {
        var profile = Settings().getProfileManager().get(defProfile);
        if (typeof (profile) != 'undefined' && profile != null) {
            $("#profile-name").val(profile.name);
            $("#torrent-client option[value='" + profile.client + "']").attr("selected", "selected");
            $("#transport-protocol option[value='" + profile.protocol + "']").attr("selected", "selected");
            $("#web-ui-host").val(profile.host);
            $("#web-ui-port").val(profile.port);
            $("#web-ui-user").val(profile.user);
            $("#web-ui-pass").val(profile.password);
        }
    }
}

function refreshProfilesList(defProfile) {
    fillProfilesList($("#default-profile"));
    if (typeof (defProfile) != 'undefined' && defProfile != null) {
        $("#default-profile option[value='" + defProfile + "']").attr("selected", "selected");
    }
}